{% include "data/template-ui.html" %}
<link rel="stylesheet" type="text/css" href="/static/css/datatables/dataTables.bootstrap4.min.css" />
<link rel="stylesheet" type="text/css" href='/static/zTree/css/zTreeStyle.css'>

<style>
    #export-pdf {
        display: flex;
        flex-direction: column;
        overflow: unset;
    }
    .page-body {
        flex: 1;
        display: flex;
        flex-direction: column;
        margin: 10px 15px;
    }
    .page-body>div {
        flex: 1;
        display: flex;
        height: 50%;
    }
    .page-body .card {
        width: 50%;
        height: 100%;
        margin: 0;
        background: #fff;
    }
    .page-body .card-title {
        margin-bottom: 0;
    }
    #chart1, #chart2, #chart3, #table {
        height: 100%;
    }
    #table th, #table td, .dataTables_scrollHead th, .dataTables_scrollBody td {
        padding: 0 !important;
        font-size: 12px;
    }
    #table thead th {
        background-color: #EDF4FA;
        color: #66718E;
    }
    .dataTables_scrollHeadInner table {
        width: 100% !important;
    }
    #data_tree_wrapper {
        display: none;
        position: absolute;
        left: 197px;
        min-width: 200px;
        min-height: 300px;
        border-radius: 3px;
        box-shadow: 0 0 3px rgba(86, 96, 117, 0.7);
        background: #fff;
        z-index: 100;
        overflow: auto;
    }
    #version {
        height: 32px;
        background-color: #FFFFFF;
        background-image: none;
        border: 1px solid #e5e6e7;
        border-radius: 1px;
        padding: 0px 12px;
        transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
        font-size: 14px;
    }
    #version:focus {
        border-color: #007bff !important;
    }
    .table thead th {
        background-color: #EDF4FA;
        color: #66718E;
    }
    .table th, .table td, .dataTables_scrollHead th, .dataTables_scrollBody td {
        padding: 0 !important;
        font-size: 12px;
    }
    #table_wrapper {
        height: 100%;
    }
</style>

<div class="container-fluid animated">
    <!-- 标题 -->
    <div id="export-pdf" style="height: 100%">
        <div class="row page-titles">
            <div class="col-md-12 align-self-center" style="display: flex;align-items: center">
                <h3 class="text-primary" style="margin-right: 30px">趋势分析</h3>
                <div>
                    <label for="version" style="margin-bottom:0">数据期：</label>
                    <input id="version" name="version" type="text" autocomplete="off">
                    <div id="data_tree_wrapper">
                        <ul id="data_tree" class="ztree"></ul>
                    </div>
                </div>
                <button onclick="search();" class="btn btn-primary btn-sm" style="margin-left: 30px">
                    <i class="fa fa-search"></i>查询
                </button>
                <!--<button onclick="exportPdf();" class="btn btn-primary btn-sm" style="margin-left: 30px">-->
                    <!--<i class="fa fa-download"></i>导出pdf-->
                <!--</button>-->
            </div>
        </div>
        <div class="page-body">
            <div style="margin-bottom: 5px;">
                <div class="card" style="margin-right: 5px">
                    <div class="card-title">错误数和绩效历史趋势</div>
                    <div class="card-body">
                        <div id="chart1"></div>
                    </div>
                </div>
                <div class="card" style="margin-left: 5px">
                    <div class="card-title">各规则错误数及占比情况</div>
                    <div class="card-body">
                        <div id="chart2"></div>
                    </div>
                </div>
            </div>
            <div style="margin-top: 5px;">
                <div class="card" style="display: flex;flex-direction: column;margin-right: 5px">
                    <div class="card-title">各表错误数详细情况分析</div>
                    <div class="card-body table-card" style="flex: 1;height: 0;position: relative">
                        <div class="table-loading" style="display: none">加载中...</div>
                        <table id="table" class="table table-bordered" cellspacing="0" width="100%">
                            <thead>
                            <tr>
                                <th>规则名</th>
                                <th>子规则名</th>
                                <th>规则类型</th>
                                <th>问题类型</th>
                                <th>错误统计</th>
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
                <div class="card" style="margin-left: 5px">
                    <div class="card-title">各检查表错误数及占比情况</div>
                    <div class="card-body">
                        <div id="chart3"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</div>
</div>

<script type="text/javascript" src="/static/js/DataTables/datatables.min.js"></script>
<!--<script type="text/javascript" src="/static/js/DataTables/DataTables-1.10.18/js/dataTables.bootstrap.js"></script>-->
<script src='/static/zTree/js/jquery.ztree.core.min.js'></script>
<script src='/static/zTree/js/fuzzysearch.js'></script>
<script src='/static/zTree/js/jquery.ztree.exhide.min.js'></script>
<script src='/static/zTree/js/jquery.ztree.exedit.js'></script>
<script src="/static/js/html2pdf.bundle.min.js"></script>

<script type="text/javascript" class="init">
    let company = "{{ company }}";
    let setting = {
        data: {
            key: {
                name: 'id',
                title: 'id'
            },
            simpleData: {
                enable: true,
                pIdKey: 'pid'
            }
        },
        callback: {
            onClick: onNodeClick
        },
    };
    let color = ["#67ca29", "#2da1f9", "#ff9f05", "#f46462"];
    let option1 = {
        color: ["#01b300", "#1dcbfe", "#ff9f05"],
        grid: {
            left: 40,
            top: 40,
            bottom: 40,
            right: 40
        },
        tooltip: {
            trigger: 'axis'
        },
        xAxis: {
            type: 'category',
            data: ['2021年1月']
        },
        yAxis: [{
            name: '数量',
            type: 'value',
            // min: 0,
            // max: '',
            // interval: '',
            splitLine: {
                show: true,
                lineStyle:{
                    type:'dashed'
                }
            }
        }, {
            name: '分数',
            type: 'value',
            // min: 0,
            // max: '',
            // interval: '',
            axisLabel: {
                show: true,
                interval: 'auto', //居中显示
            },
        }],
        legend: {
            data: ['检查数', '错误数', '绩效']
        },
        series: []
    };
    let option2 = {
        color: color,
        grid: {
            left: 40,
            top: 40,
            bottom: 40,
            right: 40
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            x: 'right',
            data: []
        },
        series: [{
            name: '',
            type: 'pie',
            data: []
        }]
    };
    let option3 = {
        color: color,
        grid: {
            left: 40,
            top: 40,
            bottom: 40,
            right: 40
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            x: 'right',
            data: []
        },
        series: [{
            name: '',
            type: 'pie',
            data: []
        }]
    };

    $(document).ready(function () {
        initSearch();
        getVersionTree().then(res => {
            if (res.stat !== 200) return;
            initVersionTree(res.data);
            search();
        });
    });

    // 获取树的数据
    function getVersionTree() {
        return $post("../../api/dashboard/model_page_info_version_all", {
            company: company,
            startTime: $('#datepicker-start').val(),
            endTime: $('#datepicker-end').val()
        }).then(result => {
            return result;
        }).catch(e => {
            console.error(e);
        });
    }

    // 初始化树
    function initVersionTree(data) {
        let tree = $.fn.zTree.init($("#data_tree"), setting, data);
        fuzzySearch('data_tree', '#version', null, null); //初始化模糊搜索方法
        tree.expandNode(tree.getNodeByTId('data_tree_1'));
        let firstChildNode = tree.getNodeByTId('data_tree_2');
        if (firstChildNode) {
            tree.selectNode(firstChildNode);
        }
        $('#version').val(firstChildNode.id);
        $('#version').attr('version', firstChildNode.check_version);
    }

    //初始化搜索
    function initSearch() {
        $('#version').click(function() {
            $('#data_tree_wrapper').css('display', 'block');
        });
        $('#version').blur(function() {
            $('#data_tree_wrapper').css('display', 'none');
        });
        $("#data_tree_wrapper").on("mousedown ", function () {
            event.preventDefault();
        });
    }

    // 导出成pdf
    function exportPdf() {
        let ele = document.getElementById('export-pdf');
        let option = {
            margin: [0, 0],
                filename: '趋势分析.pdf',
            image: {
            type: 'jpeg',
                quality: 0.98
            },
            html2canvas: {
                dpi: 192,
                    scale:2,
                    letterRendering: true
            },
            jsPDF: {
                unit: 'mm',
                format: 'a4',
                orientation: 'landscape'
            }
        };
        html2pdf().from(ele).set(option).save();
    }

    // 点击进行查询
    function search() {
        let version = $('#version').attr('version');
        option1.series = [];
        option2.series[0].data = [];
        option3.series[0].data = [];
        setChart1(version);
        setChart2(version);
        setChart3(version);
        setTable(version);
    }

    // 点击数的节点
    function onNodeClick(event, treeId, treeNode, clickFlag) {
        if (!treeNode.isParent) {
            $('#version').blur(function() {
                $('#data_tree_wrapper').css('display', 'none');
            });
            $('#version').val(treeNode.id);
            $('#version').attr('version', treeNode.check_version);
            $('#data_tree_wrapper').css('display', 'none');
        }
    }

    function setChart1(version) {
        let chart1 = echarts.init(document.getElementById('chart1'));
        showLoading(chart1);
        $post("../../api/quality/model_history_trend", {
            company: company,
            check_version: version
        }).then(res => {
            if (res.stat != 200) {
                showText($('#chart1'), '请求失败');
                return;
            }

            if (res.data.length  === 0) {
                showText($('#chart1'), '暂无数据');
            } else {
                hideText($('#chart1'));
                let xAxis = [], result = [], result_err = [],total_coefficient = [];
                res.data.forEach(v => {
                    xAxis.push(v.check_version);
                    result.push(v.result);
                    result_err.push(v.result_err);
                    total_coefficient.push(v.total_coefficient);
                });

                // let leftInterval = '', rightInterval = '';
                // leftInterval = Math.ceil(Math.max(...result, ...result_err) / 5);
                // rightInterval = Math.ceil(Math.max(...total_coefficient) / 5);
                // option1.yAxis[0].interval = leftInterval;
                // option1.yAxis[1].interval = rightInterval;
                // option1.yAxis[0].max = leftInterval * 5;
                // option1.yAxis[1].max = rightInterval * 5;
                option1.xAxis.data = xAxis;
                option1.series = [{
                    type: 'bar',
                    barMaxWidth: 150,
                    name: '检查数',
                    data: result,
                }, {
                    type: 'bar',
                    barMaxWidth: 150,
                    name: '错误数',
                    data: result_err
                }, {
                    type: 'line',
                    name: '绩效',
                    data: total_coefficient,
                    yAxisIndex: 1
                }];
                chart1.setOption(option1);
                hideLoading(chart1);
            }
        }).catch(e => {
            console.error(e);
            showText($('#chart1'), '请求失败');
        });
    }

    function setChart2(version) {
        let chart2 = echarts.init(document.getElementById('chart2'));
        showLoading(chart2);
        $post("../../api/quality/model_rule_error", {
            company: company,
            check_version: version
        }).then(res => {
            if (res.stat != 200) {
                showText($('#chart2'), '请求失败');
                return;
            }

            hideText($('#chart2'));
            res.data.forEach(v => {
                option2.legend.data.push(v.problem_type);
                option2.series[0].data.push({ name: v.problem_type, value: v.result },)
            });
            chart2.setOption(option2);
            hideLoading(chart2);
        }).catch(e => {
            console.error(e);
            showText($('#chart2'), '请求失败');
        });
    }

    function setChart3(version) {
        let chart3 = echarts.init(document.getElementById('chart3'));
        showLoading(chart3);
        $post("../../api/quality/model_target_table_detail", {
            company: company,
            check_version: version
        }).then(res => {
            if (res.stat != 200) {
                showText($('#chart3'), '请求失败');
                return;
            }

            hideText($('#chart3'));
            res.data.forEach(v => {
                option3.legend.data.push(v.target_table);
                option3.series[0].data.push({ name: v.target_table, value: v.result_err },)
            });
            chart3.setOption(option3);
            hideLoading(chart3);
        }).catch(e => {
            console.error(e);
            showText($('#chart3'), '请求失败');
        });
    }

    function setTable(version) {
        $('.table-loading').removeAttr('style');
        let maxHeight = $('.table-card').height();
        $post("../../api/quality/model_history_rule_detail", {
            company: company,
            check_version: version
        }).then(res => {
            if (res.stat != 200) return;

            $('#table').DataTable({
                destroy: true,
                searching: false,
                ordering: false,
                info: false,
                paging: false,
                scrollY: maxHeight - 53,
                scrollCollapse: true,
                fixedHeader: true, // 固定表头
                data: res.data,
                columns: [
                    { data: 'note'},
                    { data: 't_name' },
                    { data: 'type' },
                    { data: 'problem_type'},
                    { data: 'result_err'}
                ],
                columnDefs: [{
                    targets: 2,
                    data: null,
                    render: function (data, type, row) {
                        return data === 'numerator' ? '分子' : '分母';
                    }
                }]
            });

            // 修复表头错位的问题
            // let scrollHeadInner = $('#table_wrapper .dataTables_scrollHeadInner');
            // let scrollBody = $('#table_wrapper .dataTables_scrollBody');
            // if (scrollHeadInner.width() < scrollBody.width()) {
            //     scrollHeadInner.css('width', +scrollHeadInner.css('width').replace('px', '') + 13 + 'px');
            // }

            $('.table-loading').css('display', 'none');
        }).catch(e => {
            $('.table-loading').css('display', 'none');
        });
    }

    function showLoading(chart) {
        chart.showLoading({
            text: '加载中...',
            textStyle: { fontSize : 30 , color: '#60acfc' },
            effectOption: { backgroundColor: 'rgba(0, 0, 0, 0)' }
        });
    }

    function hideLoading(chart) {
        chart.hideLoading();
    }
</script>
</body>
</html>